/**
 * TikTok商品视频信息模型
 * 对应数据库表 t_product_videos
 */

const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const ProductVideo = sequelize.define('ProductVideo', {
    id: {
        type: DataTypes.STRING(50),
        primaryKey: true,
        allowNull: false,
        comment: '视频ID（接口获取的视频ID）'
    },
    origin_cover: {
        type: DataTypes.TEXT,
        allowNull: true,
        comment: '视频封面图URL'
    },
    product_id: {
        type: DataTypes.STRING(50),
        allowNull: false,
        comment: '关联商品ID',
        references: {
            model: 't_product',
            key: 'id'
        }
    },
    desc: {
        type: DataTypes.TEXT,
        allowNull: true,
        comment: '视频描述'
    },
    video_duration: {
        type: DataTypes.INTEGER,
        allowNull: true,
        comment: '视频时长（秒）'
    },
    video_link: {
        type: DataTypes.STRING(500),
        allowNull: true,
        comment: '视频链接'
    },
    total_estimated_sales_amount: {
        type: DataTypes.DECIMAL(15, 2),
        allowNull: true,
        comment: '预估销售额（GMV）'
    },
    total_estimated_sales_volume: {
        type: DataTypes.INTEGER,
        allowNull: true,
        comment: '预估销量（Order）'
    },
    play_count: {
        type: DataTypes.BIGINT,
        allowNull: true,
        comment: '播放量'
    },
    digg_count: {
        type: DataTypes.BIGINT,
        allowNull: true,
        comment: '点赞数'
    },
    comment_count: {
        type: DataTypes.BIGINT,
        allowNull: true,
        comment: '评论数'
    },
    share_count: {
        type: DataTypes.BIGINT,
        allowNull: true,
        comment: '分享数'
    },
    author_last_time: {
        type: DataTypes.STRING(50),
        allowNull: true,
        comment: '发布日期'
    },
    author_last_time_stamp: {
        type: DataTypes.DATE,
        allowNull: true,
        comment: '发布日期时间戳'
    },
    author_id: {
        type: DataTypes.STRING(100),
        allowNull: true,
        comment: 'KOL ID'
    },
    author_unique_id: {
        type: DataTypes.STRING(100),
        allowNull: true,
        comment: 'KOL唯一ID'
    },
    author_nickname: {
        type: DataTypes.STRING(200),
        allowNull: true,
        comment: 'KOL昵称'
    },
    sys_country_country: {
        type: DataTypes.STRING(100),
        allowNull: true,
        comment: '国家英文名'
    },
    sys_country_country_cn: {
        type: DataTypes.STRING(100),
        allowNull: true,
        comment: '国家中文名'
    },
    sys_country_country_code: {
        type: DataTypes.STRING(10),
        allowNull: true,
        comment: '国家代码'
    },
    author_follower_count: {
        type: DataTypes.BIGINT,
        allowNull: true,
        comment: 'KOL粉丝数'
    },
    author_homepage: {
        type: DataTypes.STRING(500),
        allowNull: true,
        comment: 'KOL账号主页'
    },
    createTime: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        comment: '创建时间'
    },
    updateTime: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        comment: '更新时间'
    }
}, {
    tableName: 't_product_videos',
    timestamps: true,
    createdAt: 'createTime',
    updatedAt: 'updateTime',
    comment: 'TikTok商品视频信息表',

    indexes: [
        {
            name: 'idx_product_videos_product_id',
            fields: ['product_id']
        },
        {
            name: 'idx_product_videos_author_id',
            fields: ['author_id']
        },
        {
            name: 'idx_product_videos_author_unique_id',
            fields: ['author_unique_id']
        },
        {
            name: 'idx_product_videos_author_nickname',
            fields: ['author_nickname']
        },
        {
            name: 'idx_product_videos_play_count',
            fields: ['play_count']
        },
        {
            name: 'idx_product_videos_digg_count',
            fields: ['digg_count']
        },
        {
            name: 'idx_product_videos_comment_count',
            fields: ['comment_count']
        },
        {
            name: 'idx_product_videos_share_count',
            fields: ['share_count']
        },
        {
            name: 'idx_product_videos_author_follower_count',
            fields: ['author_follower_count']
        },
        {
            name: 'idx_product_videos_total_estimated_sales_amount',
            fields: ['total_estimated_sales_amount']
        },
        {
            name: 'idx_product_videos_total_estimated_sales_volume',
            fields: ['total_estimated_sales_volume']
        },
        {
            name: 'idx_product_videos_author_last_time_stamp',
            fields: ['author_last_time_stamp']
        },
        {
            name: 'idx_product_videos_sys_country_country',
            fields: ['sys_country_country']
        },
        {
            name: 'idx_product_videos_sys_country_code',
            fields: ['sys_country_country_code']
        },
        {
            name: 'idx_product_videos_create_time',
            fields: ['createTime']
        },
        {
            name: 'idx_product_videos_update_time',
            fields: ['updateTime']
        }
    ]
});

/**
 * 定义关联关系
 */
ProductVideo.associate = function (models) {
    // 多对一关联：一个商品可以有多个视频
    ProductVideo.belongsTo(models.Product, {
        foreignKey: 'product_id',
        targetKey: 'id',
        as: 'product',
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE'
    });
};

/**
 * 生成视频链接的静态方法
 * @param {string} authorUniqueId - KOL唯一ID
 * @param {string} videoId - 视频ID
 * @returns {string} 完整的视频链接
 */
ProductVideo.generateVideoLink = function (authorUniqueId, videoId) {
    if (!authorUniqueId || !videoId) {
        return null;
    }
    return `https://www.tiktok.com/@${authorUniqueId}/video/${videoId}`;
};

/**
 * 生成KOL主页链接的静态方法
 * @param {string} authorNickname - KOL昵称
 * @returns {string} KOL主页链接
 */
ProductVideo.generateAuthorHomepage = function (authorNickname) {
    if (!authorNickname) {
        return null;
    }
    return `https://www.tiktok.com/@${authorNickname}`;
};

/**
 * 实例方法：格式化视频时长为可读格式
 * @returns {string} 格式化后的时长，如 "1:30"
 */
ProductVideo.prototype.getFormattedDuration = function () {
    if (!this.video_duration) {
        return '未知';
    }

    const minutes = Math.floor(this.video_duration / 60);
    const seconds = this.video_duration % 60;
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
};

/**
 * 实例方法：格式化播放量为可读格式
 * @returns {string} 格式化后的播放量，如 "1.2M"、"850K"
 */
ProductVideo.prototype.getFormattedPlayCount = function () {
    if (!this.play_count) {
        return '0';
    }

    const count = parseInt(this.play_count);

    if (count >= 1000000) {
        return (count / 1000000).toFixed(1) + 'M';
    } else if (count >= 1000) {
        return (count / 1000).toFixed(1) + 'K';
    } else {
        return count.toString();
    }
};

/**
 * 实例方法：格式化粉丝数为可读格式
 * @returns {string} 格式化后的粉丝数，如 "1.2M"、"850K"
 */
ProductVideo.prototype.getFormattedFollowerCount = function () {
    if (!this.author_follower_count) {
        return '0';
    }

    const count = parseInt(this.author_follower_count);

    if (count >= 1000000) {
        return (count / 1000000).toFixed(1) + 'M';
    } else if (count >= 1000) {
        return (count / 1000).toFixed(1) + 'K';
    } else {
        return count.toString();
    }
};

module.exports = ProductVideo;